using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace AnimationPage.ViewModels;

public partial class TextEntryViewModel : ViewModelBase
{
    [ObservableProperty] private string? _label;

    [ObservableProperty] private string? _originalText;

    [ObservableProperty] private string? _editedText;

    [ObservableProperty] private bool _editing;

    [ObservableProperty] private bool _working;

    public Func<Task<bool>> CommitAction { get; set; }

    /// <summary>
    /// Puts the control into edit mode
    /// </summary>
    [RelayCommand]
    private void Edit()
    {
        // Set the edited text to the current value
        EditedText = OriginalText;

        // Go into edit mode
        Editing = true;
    }

    /// <summary>
    /// Cancels out of edit mode
    /// </summary>
    [RelayCommand]
    private void Cancel()
    {
        Editing = false;
    }

    /// <summary>
    /// Commits the content and exits out of edit mode
    /// </summary>
    [RelayCommand]
    private void Save()
    {
        // Store the result of a commit call
        var result = default(bool);

        // Save currently saved value
        var currentSavedValue = OriginalText;

        RunCommandAsync(() => Working, async () =>
        {
            // While working, come out of edit mode
            Editing = false;

            await Task.Delay(5000);
            // Commit the changed text
            // So we can see it while it is working
            OriginalText = EditedText;

            // Try and do the work
            result = CommitAction == null ? true : await CommitAction();
        }).ContinueWith(t =>
        {
            // If we succeeded...
            // Nothing to do
            // If we fail...
            if (!result)
            {
                // Restore original value
                OriginalText = currentSavedValue;

                // Go back into edit mode
                Editing = true;
            }
        });
    }
}